<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showOkBtn="false"
  >
    <div class="flex flex-col justify-center" v-if="!isShowEdit">
      <BasicForm @register="registerForm">
        <template #file>
          <FormItemRest>
            <Space>
              <Upload
                :file-list="fileList"
                :before-upload="beforeUpload"
                @remove="handleRemove"
                :maxCount="1"
                @change="handleChange"
              >
                <a-button>
                  <UploadOutlined />
                  选择文件
                </a-button>
              </Upload>
              <Checkbox v-model:checked="state['isBatch']">批量</Checkbox>
            </Space>
          </FormItemRest>
        </template>
      </BasicForm>
      <div class="text-center">
        <a-button type="primary" @click="handleSubmitFile" :loading="loading">确定</a-button>
      </div>
    </div>
    <div v-if="isShowEdit">
      <ImportComponentEdit
        :isBatch="state['isBatch']"
        :formCode="formCode"
        :stateData="stateData"
        :loading="loading"
        :isUpdate="isUpdate"
        @success="handleImportComponentEdit"
      />
    </div>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Upload, UploadProps, Checkbox, Form, Space } from 'ant-design-vue';
  import { formSchema } from './importComponent.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import ImportComponentEdit from './modules/ImportComponentEdit.vue';
  import {
    getVisualUploadTemplate,
    getVisualEditImportPage,
    getVisualCreateImportCells,
    getVisualCreateImportCols,
    getVisualUpdateImportCols,
    getVisualUpdateImportCells,
  } from '/@/api/module/module';
  import { isArray } from '/@/utils/is';

  export default defineComponent({
    name: 'ImportComponentDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      Upload,
      Checkbox,
      FormItemRest: Form.ItemRest,
      UploadOutlined,
      Space,
      ImportComponentEdit,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const loading = ref(false);
      const fileList = ref<UploadProps['fileList']>([]);
      const moduleCode = ref('');
      const formCode = ref('');
      const state = ref({
        cols: [],
        cells: [],
        basicFields: [],
        xlsTmpPath: '',
        isBatch: true,
        name: '',
        rules: [],
      });
      const stateData = ref<Recordable>({
        name: '',
        cols: [],
        cells: [],
        basicFields: [],
        id: -1,
      });
      const isShowEdit = ref(false);
      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const width = ref('85%');

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false, showOkBtn: false });
        isUpdate.value = !!data?.isUpdate;
        moduleCode.value = data?.moduleCode;
        formCode.value = data?.formCode;
        fileList.value = [];
        stateData.value.cols = [];
        stateData.value.cells = [];
        stateData.value.basicFields = [];
        if (unref(isUpdate)) {
          isShowEdit.value = true;
          const record = data?.record ?? {};
          state.value = await getVisualEditImportPage({ id: record.id });
          console.log('state.value', state.value);
          stateData.value.basicFields = state.value.basicFields;
          stateData.value.name = state.value.name;
          stateData.value.id = record.id;
          if (state.value.isBatch) {
            stateData.value.cols = state.value.rules;
          } else {
            const _cells = state.value.cells ? state.value.cells.replaceAll('\n', '&#') : '';
            const newCells: Recordable[] = state.value.cells ? JSON.parse(_cells) : [];
            console.log('newCells', newCells);
            console.log('newCells TYPE', typeof newCells);

            if (isArray(newCells) && newCells.length) {
              const len = Math.max(
                ...newCells.map((item: any) => (isArray(item) ? item.length : 0)),
              );
              console.log('len', len);
              newCells.forEach((item: any, index) => {
                if (isArray(item)) {
                  stateData.value.cells.push([]);
                  item.forEach((el) => {
                    stateData.value.cells[index].push({
                      title: el,
                      name: '',
                      fieldName: '',
                    });
                  });
                  if (item.length != len) {
                    for (let i = item.length; i < len; i++) {
                      stateData.value.cells[index].push({
                        title: '',
                        name: '',
                        fieldName: '',
                      });
                    }
                  }
                } else {
                  stateData.value.cells.push([]);
                }
              });
            }
            if (isArray(state.value.rules) && state.value.rules.length) {
              state.value.rules.forEach((item) => {
                stateData.value.cells.forEach((el, mi) => {
                  el.forEach((cl, ci) => {
                    if (item.r == mi && item.c == ci) {
                      cl.name = item.field;
                    }
                  });
                });
              });
            }
          }
          console.log('stateData.value', stateData.value);
        } else {
          isShowEdit.value = false;
          state.value.isBatch = true;
        }
      });
      function stringToArray(arr) {
        return arr.map((item) => {
          if (typeof item === 'string' && item[0] === '[' && item[item.length - 1] === ']') {
            return stringToArray(JSON.parse(item));
          }
          return item;
        });
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        // try {
        //   const values = await validate();
        //   let formDate = Object.assign({}, values);
        //   setDrawerProps({ confirmLoading: true });
        //   console.log(formDate);
        //   closeDrawer();
        //   emit('success');
        // } finally {
        //   setDrawerProps({ confirmLoading: false });
        // }
      }
      //上传前校验
      const beforeUpload: UploadProps['beforeUpload'] = (file) => {
        fileList.value = [file];
        return false;
      };
      //上传change
      const handleChange = (e) => {
        console.log('e', e);
      };
      // 上传文件删除
      const handleRemove: UploadProps['onRemove'] = (file) => {
        const index = fileList.value!.indexOf(file);
        const newFileList = fileList.value!.slice();
        newFileList.splice(index, 1);
        fileList.value = newFileList;
      };

      //上传文件确定
      const handleSubmitFile = async () => {
        try {
          if (fileList.value!.length == 0) {
            createMessage.warning('请选择文件');
            return;
          }
          setDrawerProps({ confirmLoading: true });
          let params = {
            file: fileList.value![0],
            isBatch: state.value.isBatch ? 1 : 0,
            moduleCode: moduleCode.value,
          };
          let formData = new FormData();
          for (let v in params) {
            formData.append(v, params[v]);
          }
          console.log(params);
          loading.value = true;
          const res = await getVisualUploadTemplate(formData);
          console.log('res', res);
          state.value = Object.assign(state.value, res);
          stateData.value.name = '';
          stateData.value.cols = [];
          stateData.value.cells = [];
          stateData.value.basicFields = state.value.basicFields || [];
          stateData.value.basicFields.forEach((item) => {
            if (isArray(item.options) && item.options.length) {
              item.options.forEach((el) => {
                el.otherVal = el.name;
              });
            }
          });

          if (isArray(state.value.cols) && state.value.cols.length) {
            state.value.cols.forEach((item) => {
              stateData.value.cols.push({
                title: item,
                field: '',
                canNotRepeat: 0,
                canNotEmpty: 0,
              });
            });
          }
          if (isArray(state.value.cells) && state.value.cells.length) {
            const len = Math.max(
              ...state.value.cells.map((item: any) => (isArray(item) ? item.length : 0)),
            );
            console.log('len', len);
            state.value.cells.forEach((item: any, index) => {
              if (isArray(item)) {
                stateData.value.cells.push([]);
                item.forEach((el) => {
                  stateData.value.cells[index].push({
                    title: el,
                    field: '',
                    fieldName: '',
                  });
                });
                if (item.length != len) {
                  for (let i = item.length; i < len; i++) {
                    stateData.value.cells[index].push({
                      title: '',
                      field: '',
                      fieldName: '',
                    });
                  }
                }
              } else {
                stateData.value.cells.push([]);
              }
            });
          }
          isShowEdit.value = true;
          console.log({
            stateData: stateData.value,
            state: state.value,
          });
        } catch (error) {
          console.error(error);
        } finally {
          setDrawerProps({ confirmLoading: false });
          loading.value = false;
        }
      };

      //最终保存确定
      const handleImportComponentEdit = async (e) => {
        console.log('handleImportComponentEdit', e);
        try {
          let formData: Recordable = {};
          if (!unref(isUpdate)) {
            if (state.value['isBatch']) {
              const { dataSource, basicFields } = e;
              formData = {
                isBatch: state.value['isBatch'],
                xlsTmpPath: state.value.xlsTmpPath,
                rules: dataSource,
                basicFields,
              };
            } else {
              const { cells, basicFields } = e;
              const rules = [] as any;
              if (isArray(cells) && cells.length) {
                cells.forEach((item, index) => {
                  item.forEach((el, eli) => {
                    if (el.name) {
                      rules.push({
                        r: index,
                        c: eli,
                        field: el.name,
                      });
                    }
                  });
                });
              }
              formData = {
                isBatch: state.value['isBatch'],
                xlsTmpPath: state.value.xlsTmpPath,
                cells: state.value.cells,
                rules,
                basicFields,
              };
            }
            formData.name = e.name;
            formData.moduleCode = moduleCode.value;
            formData.formCode = formCode.value;

            console.log('formData', formData);
            loading.value = true;

            if (state.value['isBatch']) {
              await getVisualCreateImportCols({ ...formData });
            } else {
              await getVisualCreateImportCells({ ...formData });
            }
            createMessage.success('操作成功');
          } else {
            if (state.value['isBatch']) {
              const { dataSource, basicFields } = e;
              formData = {
                isBatch: state.value['isBatch'],
                // xlsTmpPath: state.value.xlsTmpPath,//没返回这个值
                rules: dataSource,
                basicFields,
              };
            } else {
              const { cells, basicFields } = e;
              const rules = [] as any;
              if (isArray(cells) && cells.length) {
                cells.forEach((item, index) => {
                  item.forEach((el, eli) => {
                    if (el.name) {
                      rules.push({
                        r: index,
                        c: eli,
                        field: el.name,
                      });
                    }
                  });
                });
              }
              formData = {
                isBatch: state.value['isBatch'],
                basicFields,
                rules,
                cells: stateData.value.cells,
              };
            }
            formData.name = e.name;
            formData.moduleCode = moduleCode.value;
            formData.formCode = formCode.value;
            formData.id = stateData.value.id;
            console.log('formData', formData);

            loading.value = true;
            if (state.value['isBatch']) {
              await getVisualUpdateImportCols({ ...formData });
            } else {
              await getVisualUpdateImportCells({ ...formData });
            }
            createMessage.success('操作成功');
          }

          closeDrawer();
          emit('success');
        } catch (error) {
          console.error(error);
        } finally {
          loading.value = false;
        }
      };

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        fileList,
        beforeUpload,
        handleChange,
        handleRemove,
        state,
        handleSubmitFile,
        loading,
        isUpdate,
        stateData,
        isShowEdit,
        handleImportComponentEdit,
        formCode,
        width,
      };
    },
  });
</script>
<style lang="less" scoped>
  :deep(.ant-row) {
    justify-content: center;
  }
</style>
